﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Cuckoo.TaskSchedule
{
	/// <summary>
	/// 任务处理策略辅助类
	/// </summary>
	internal static class TaskStrategyHelper
	{
		/// <summary>
		/// 提取任务时间表达式中对应的结点
		/// </summary>
		/// <param name="strExpress">时间表达式</param>
		/// <param name="strPattern">模式</param>
		/// <returns>对应结点的值</returns>
		public static int GetSection(string strExpress, string strPattern)
		{
			Match match = Regex.Match(strExpress, strPattern);
			if (match.Groups.Count > 0)
			{
				//表示用户没有提供该结点
				if (String.IsNullOrEmpty(match.Groups[0].Value))
				{
					return 0;
				}
				string value = match.Groups[0].Value.Substring(2, match.Groups[0].Value.Length - 4);
				int res = -1;
				//结点值不是数字格式
				if (!Int32.TryParse(value, out res))
				{
					throw new ExpressionException(match.Groups[0].Value);
				}
				if(res >= -1)
				{
					return res;
				}
				//结点值小于0
				throw new ExpressionException(match.Groups[0].Value);
			}
			return 0;
		}

		/// <summary>
		/// 提取任务时间表达式中对应的结点
		/// </summary>
		/// <param name="strExpress">时间表达式</param>
		/// <param name="type">结点名称</param>
		/// <param name="flag">占位参数</param>
		/// <returns>对应结点的值</returns>
		public static int GetSection(string strExpress, string type, bool flag)
		{
			string strPattern = String.Format(@"/{0}-?[0-9]*/{0}", type);
			return GetSection(strExpress, strPattern);
		}

		/// <summary>
		/// 根据任务的时间表达式获取任务的类型
		/// </summary>
		/// <param name="task"></param>
		/// <returns></returns>
		public static TaskType GetType(ITask task)
		{
			string type = task.ScheduleExpress.Substring(0, task.ScheduleExpress.IndexOf('$'));
			switch (type.ToUpper())
			{
				case "I":
					return TaskType.INTERNAL_TASK;
				case "S":
					return TaskType.SOLID_TASK;
				default:
					throw new ExpressionException(task.ScheduleExpress);
			}
        }

        /// <summary>
        /// 根据年月计算出第num个星期day是当月的第几天
        /// </summary>
        /// <param name="year">年</param>
        /// <param name="month">月</param>
        /// <param name="num">第几个星期</param>
        /// <param name="day">星期几</param>
        /// <returns>第num个星期day对应的天数</returns>
        public static int GetTotalByNumAndDay(int year, int month, int num, int day)
        {
            int temp = day == 7 ? 1 : day + 1;
            DateTime time = new DateTime(year, month, 1);
            int week = (int)time.DayOfWeek + 1;
            int total = 0;
            if (temp < week)
            {
                total = (num - 1) * 7 + temp + 7 - week + 1;
            }
            else if (temp > week)
            {
                total = (num - 1) * 7 + temp - week + 1;
            }
            else
            {
                total = (num - 1) * 7 + 1;
            }
            return total;
        }
    }
}
